package com.example.bluetooth.le;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.brtbeacon.sdk.BRTBeacon;
import com.brtbeacon.sdk.BRTBeaconConfig;
import com.brtbeacon.sdk.BRTBeaconConnection;
import com.brtbeacon.sdk.BRTThrowable;
import com.brtbeacon.sdk.Hardware;
import com.brtbeacon.sdk.IBle;
import com.brtbeacon.sdk.callback.BRTBeaconConnectionListener;
import com.brtbeacon.sdk.callback.BRTBeaconFirmWareUpdateListener;

/**
 * Beacon连接
 */
public class TestControlActivity extends Activity {
	private final static String TAG = TestControlActivity.class.getSimpleName();

	public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
	public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

	private TextView mConnectionState;
	private TextView mValues;
	private String mDeviceName;
	private String mDeviceAddress;
	private boolean mConnected = false;
	protected IBle mBle;

	private BRTBeaconConnection beaconConnection;
	private BRTBeacon mBeacon;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gatt_services_characteristics);

		final Intent intent = getIntent();
		mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
		mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
		mBeacon = intent.getParcelableExtra("TAG");
		// Sets up UI references.
		((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);

		mConnectionState = (TextView) findViewById(R.id.connection_state);
		mValues = (TextView) findViewById(R.id.connection_values);
		findViewById(R.id.connection_values_write_uuid).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (beaconConnection.isConnected()) {
					// 设置参数
					BRTBeaconConfig config = new BRTBeaconConfig();
					config.setUuid("0000000000000000000000000000002B");
					config.setMajor(10000);
					config.setMinor(10001);
					config.setName("L001");
					// 更新参数
					beaconConnection.writeValues(config);
				}
			}
		});
		findViewById(R.id.connection_values_update_firm).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (beaconConnection.isConnected()) {
					// 检查固件是否可更新
					beaconConnection.checkBeaconFirmWare();
				}
			}
		});

		getActionBar().setTitle(mDeviceName);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		BleApplication app = (BleApplication) getApplication();
		mBle = app.getIBle();
		beaconConnection = new BRTBeaconConnection(this, mBle, mBeacon, new BRTBeaconConnectionListener() {

			@Override
			public void onConnectedState(BRTBeacon beacon, int newState, int status) {
				// 连接状态 BRTBeaconConnection.CONNECTED or
				// BRTBeaconConnection.DISCONNECTED
				if (newState == BRTBeaconConnection.CONNECTED) {
					mConnected = true;
					updateConnectionState(R.string.connected);
					invalidateOptionsMenu();
				} else {
					Toast.makeText(TestControlActivity.this, "连接断开" + status, Toast.LENGTH_LONG).show();
					onDeviceDisconnected();
				}
			}

			@Override
			public void onAuthentication(BRTBeacon beacon) {
				// 验证APPKEY成功回调
				Toast.makeText(TestControlActivity.this, "APPKEY验证通过", Toast.LENGTH_SHORT).show();

				bindView(beacon);
			}

			@Override
			public void onUpdateBeaconSuccess(BRTBeacon beacon, int status) {
				// 更新Beacon参数
				Toast.makeText(TestControlActivity.this, "更新参数成功", Toast.LENGTH_SHORT).show();

				bindView(beacon);
			}

			@Override
			public void onFirmWareUpdate(final Hardware hardware) {
				// checkBeaconFirmWare(); 检查固件方法回调此方法
				runOnUiThread(new Runnable() {
					public void run() {
						if (beaconConnection.isConnected() && hardware.isNeedUpdate()) {
							// 固件可更新，更新固件
							beaconConnection.updateBeaconFirmWare(hardware, new BRTBeaconFirmWareUpdateListener() {

								@Override
								public void onProgress(int progress, int max) {
									System.out.println("升级固件>>>>>" + progress + "/" + max);
								}

								@Override
								public void onError(BRTThrowable throwable) {
									System.out.println("升级固件异常>>>>>");
								}
							});
						} else {
							Toast.makeText(TestControlActivity.this, "当前是最新固件", Toast.LENGTH_SHORT).show();
						}
					}
				});
			}

			@Override
			public void onError(BRTThrowable throwable) {
				// TODO Auto-generated method stub
				// Error回调
			}

		});
	}

	private void bindView(BRTBeacon beacon) {
		mValues.setText(String.format("name:%s\nuuid:%s\nmajor:%d\nminor:%d\ntxPower:%d\nmsPower:%d\nadvinterval:%d\nMode:%d\nBattery:%d\nTempt:%d\nLight:%d", beacon.getName(), beacon.getUuid(), beacon.getMajor(), beacon.getMinor(), beacon.getTxPower().ordinal(), beacon.getMeasuredPower(), beacon.getAdIntervalMillis(), beacon.getDeviceMode(), beacon.getBattery(), beacon.getTemperature(),
				beacon.getLight()));

	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (beaconConnection != null) {
			// 断开连接
			beaconConnection.disconnect();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.gatt_services, menu);
		if (mConnected) {
			menu.findItem(R.id.menu_connect).setVisible(true);
			menu.findItem(R.id.menu_disconnect).setVisible(true);
		} else {
			menu.findItem(R.id.menu_connect).setVisible(true);
			menu.findItem(R.id.menu_disconnect).setVisible(true);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_connect:
			// 连接
			beaconConnection.connect();
			return true;
		case R.id.menu_disconnect:
			beaconConnection.disconnect();
			onDeviceDisconnected();
			return true;
		case android.R.id.home:
			onBackPressed();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void updateConnectionState(final int resourceId) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mConnectionState.setText(resourceId);
			}
		});
	}

	private void onDeviceDisconnected() {
		mConnected = false;
		updateConnectionState(R.string.disconnected);
		invalidateOptionsMenu();
		clearUI();
	}

	private void clearUI() {
		// TODO Auto-generated method stub

	}
}
